<template>
  <div class="uInfo-root w">
    <div class="hr-10"></div>

    <div class="ui-usercenter-main">
      <div class="userInfo-fixed">
        <div class="uInfo-avtar-info">
          <img class="uInfo-avtar-img" :src="userInfo.logoUrl" />
          <div class="uc-user-name">
            <span class="uInfo-text-container"
              ><span class="uInfo-vertical-align">{{
                userInfo.username
              }}</span></span
            >
          </div>
          <div class="uc-user-name">
            <span class="uInfo-text-container"
              ><span class="uInfo-vertical-align">帐号：</span></span
            >
            <span
              class="uInfo-text-container userAccount"
              style="max-width: 155px"
              ><span class="uInfo-vertical-align">{{
                myInfo.phone
              }}</span></span
            >
          </div>
        </div>
        <div class="uInfo-usercenter-menustyle">
          <ul>
            <li>
              <div
                class="menuitem"
                :class="{ select: clickstate.nowState.PInfo.ifstate }"
                @click="changeClickState(clickstate.prewState, 'PInfo')"
              >
                <i class="iconfont">&#xe651;</i>
                <span class="uInfo-text-container menu-text"
                  ><span class="uInfo-vertical-align">个人信息</span></span
                >
              </div>
            </li>
            <li>
              <div
                class="menuitem"
                :class="{ select: clickstate.nowState.PSafety.ifstate }"
                @click="changeClickState(clickstate.prewState, 'PSafety')"
              >
                <i class="iconfont">&#xe61e;</i>
                <span class="uInfo-text-container menu-text"
                  ><span class="uInfo-vertical-align">帐号与安全</span></span
                >
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="userInfo-right">
        <div>
          <div class="uc-title">
            <span class="uInfo-text-container"
              ><span class="uInfo-vertical-align">{{
                clickstate.nowtitle
              }}</span></span
            >
          </div>
        </div>
        <!-- 个人信息div -->
        <div v-if="clickstate.nowState.PInfo.ifstate">
          <div
            id="personalInfo"
            class="uInfo-personalInfoContent uInfo-personalInfo-zh-cn"
          >
            <div>
              <div class="profilePicUpload-wrapper" @click="changeisUpImg()">
                <img :src="userInfo.logoUrl" class="uInfo-personalHeadPic" />
                <span class="uInfo-text-container personalInfoSubHeading"
                  ><span class="uInfo-vertical-align" style="margin-left: 10px"
                    >头像</span
                  ></span
                >
                <!---->
                <i class="iconfont uc-page-switch-icon">&#xe631;</i>
              </div>
              <div style="margin-top: 16px; margin-bottom: 40px">
                <div class="uInfo-common-line"></div>
              </div>
              <div class="form" id="form">
                <el-form
                  :model="pForm"
                  status-icon
                  :rules="pRules"
                  label-width="70px"
                  ref="pForm"
                >
                  <el-form-item label="昵称" prop="username">
                    <el-input
                      type="text"
                      v-model="pForm.username"
                      autocomplete="off"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model="pForm.age"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="sex">
                    <el-select
                      v-model="pForm.sex"
                      placeholder="请选择"
                      class="uInfo-input2"
                      size="mediun"
                    >
                      <el-option
                        v-for="item in sexoptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      :disabled="PFormdisabled"
                      @click="updateUerInfo()"
                      >保存</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
              <!-- <div style="text-align: center">
                <input
                  type="button"
                  id="getValiCode"
                  ht="click_personalInfo_save"
                  value="保存"
                  disabled="disabled"
                  class="uInfo-submitBtn uInfo-disabled"
                  style="margin: 30px 0px"
                />
              </div> -->
            </div>
          </div>
        </div>
        <!-- 上传头像div -->
        <div class="uInfo-dialog-root uc-avatar-dialog">
          <div
            tabindex="-1"
            class="uInfo-dialog-main"
            :class="{ displaynone: isUpImg }"
          >
            <div class="uInfo-dialog-header">
              <div>
                <span class="uInfo-text-container"
                  ><span class="uInfo-vertical-align">上传头像</span></span
                >
              </div>
              <div class="dialog-cancel">
                <el-button
                  icon="el-icon-close"
                  circle
                  @click="changeisUpImg()"
                ></el-button>
              </div>
            </div>
            <div class="uInfo-dialog-body">
              <div class="uInfo-dialog-content">
                <div id="editPicContent">
                  <imgCutter @changeImg="changeisUpImg"></imgCutter>
                  <div style="margin-left: 7px; margin-bottom: 5px">
                    <p>
                      <span class="uInfo-text-container"
                        ><span class="uInfo-vertical-align"
                          >图片格式：JPG、JPEG、PNG，大小不超过 4 MB。</span
                        ></span
                      >
                    </p>
                    <p>
                      <span class="uInfo-text-container"
                        ><span class="uInfo-vertical-align"
                          >如果图片包含不适当的内容，它将被默认图片替换。
                        </span></span
                      >
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 账号与安全div -->
        <div v-if="clickstate.nowState.PSafety.ifstate">
          <div id="uc-account-panel" class="uc-panel">
            <div class="panel-header">
              <span class="uInfo-text-container"
                ><span class="uInfo-text-container">帐号登录方式</span></span
              >
            </div>
            <div class="panel-description">
              <span class="uInfo-text-container"
                ><span class="uInfo-text-container"
                  >您可使用帐号名、手机号登录系统</span
                ></span
              >
            </div>
            <div id="uc-basicPanel">
              <ul>
                <li>
                  <div id="primaryLoginID" class="uc-basic-item-root">
                    <div class="uc-basic-item-container">
                      <div class="displayFlex left">
                        <img
                          src="https://id1.cloud.huawei.com/CAS/static_rss/rss_87/AMW/vuebuild/img/ic_list_loginid_unifided.svg"
                          class="uc-img"
                        />
                      </div>
                      <div class="parent">
                        <div class="middle">
                          <div>
                            <span class="uInfo-text-container uc-account-title"
                              ><span class="uInfo-vertical-align"
                                >帐号名</span
                              ></span
                            >
                          </div>
                          <div>
                            <span class="uInfo-text-container uc-account-value"
                              ><span class="uInfo-vertical-align"
                                ><span class="userAccount">{{
                                  myInfo.useraccount
                                }}</span></span
                              ></span
                            >
                          </div>
                        </div>
                        <div class="displayFlex right">
                          <div
                            id="changeLoginIDBtn"
                            class="uc-normal-btn"
                            @click="DialogVisible.AccountDialogVisible = true"
                          >
                            <span class="uInfo-text-container"
                              ><span class="uInfo-vertical-align"
                                >更改</span
                              ></span
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </li>
                <li>
                  <div id="primaryPhone" class="uc-basic-item-root">
                    <div class="uc-basic-item-container">
                      <div class="displayFlex left">
                        <img
                          src="https://id1.cloud.huawei.com/CAS/static_rss/rss_87/AMW/vuebuild/img/ic_list_phonenumber.svg"
                          class="uc-img"
                        />
                      </div>
                      <div class="parent">
                        <div class="middle">
                          <div>
                            <span class="uInfo-text-container uc-account-title"
                              ><span class="uInfo-vertical-align"
                                >手机号</span
                              ></span
                            >
                          </div>
                          <div>
                            <span
                              class="
                                uInfo-text-container
                                uc-account-value uc-uni-direction
                              "
                              ><span class="uInfo-vertical-align">{{
                                myInfo.phone
                              }}</span></span
                            >
                            <!---->
                          </div>
                        </div>
                        <div class="displayFlex right">
                          <div
                            id="changePhoneBtn"
                            class="uc-normal-btn"
                            @click="DialogVisible.IdentifyDialogVisible = true"
                          >
                            <span class="uInfo-text-container"
                              ><span class="uInfo-vertical-align"
                                >更改</span
                              ></span
                            >
                          </div>
                          <!---->
                        </div>
                      </div>
                    </div>
                    <div class="uc-line-separator"></div>
                  </div>
                </li>
              </ul>
            </div>
            <!-- 更改账号名 -->
            <el-dialog
              title="账号名"
              :visible.sync="DialogVisible.AccountDialogVisible"
              width="35%"
              :before-close="handleClose"
              id="accountDialog"
            >
              <span class="uInfo-text-container" style="color: rgb(0, 0, 0)"
                ><span class="uInfo-vertical-align"
                  >帐号名用于登录，只能设置一次。</span
                ></span
              >
              <el-form
                :rules="CRules"
                :model="changeForm"
                ref="changeForm"
                status-icon
                id="accountDialog"
              >
                <el-form-item label="" prop="changeUseraccount">
                  <el-input
                    type="text"
                    v-model="changeForm.changeUseraccount"
                    autocomplete="off"
                    placeholder="账号名"
                  ></el-input>
                </el-form-item>
              </el-form>

              <div class="f-rules">
                <div class="f-rules-title">
                  <span class="uInfo-text-container"
                    ><span class="uInfo-vertical-align"
                      >帐号名设置规则：</span
                    ></span
                  >
                </div>
                <div class="f-rules-desc">
                  <p class="rules-li">
                    <span class="uInfo-text-container"
                      ><span class="uInfo-vertical-align"
                        >可使用 6-30 个字母、数字、下划线、减号或其组合</span
                      ></span
                    >
                  </p>
                  <p class="rules-li">
                    <span class="uInfo-text-container"
                      ><span class="uInfo-vertical-align"
                        >只能以字母开头</span
                      ></span
                    >
                  </p>
                </div>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="DialogVisible.AccountDialogVisible = false"
                  >取 消</el-button
                >
                <el-button type="primary" @click="updateUserAccount()"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
            <!-- 身份验证 -->
            <SmsCode
              v-if="DialogVisible.IdentifyDialogVisible"
              @changeSmsstate="changeSmsstate"
              @hh="hh"
            ></SmsCode>
            <!-- 更改手机号 -->
            <ChangePhone
              v-if="DialogVisible.PhoneDialogVisible"
              @changePhoneState="changePhoneState"
              @newPhone="newPhone"
            ></ChangePhone>
            <!-- 绑定邮箱 -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  validatePhone,
  validateAge2,
  validateUseraccount,
  validateEaiReg,
} from "../../plugins/validator";
import { mapState } from "vuex";
import imgCutter from "@/components/personalInfo/imgCutter";
import SmsCode from "@/components/personalInfo/SmsCode";
import ChangePhone from "@/components/personalInfo/ChangePhone";
export default {
  components: {
    imgCutter,
    SmsCode,
    ChangePhone,
  },
  data() {
    var checkUsername = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/;
      if (!value) {
        callback(new Error("请输入用户名"));
      } else if (value.length < 1 || value.length > 7) {
        callback(new Error("长度在 1 到 6 个字符"));
      } else if (!reg.test(value)) {
        callback(new Error("姓名不支持特殊字符"));
      } else {
        setTimeout(() => {
          if (value != this.myInfo.username) {
            this.axios
              .post("/user/Isun", {
                username: this.pForm.username,
              })
              .then((res) => {
                if (res.data.data.code == 201) {
                  callback();
                } else {
                  callback(new Error("用户名已存在"));
                }
              });
          } else {
            callback();
          }
        }, 100);
      }
    };
    return {
      //切换状态
      clickstate: {
        prewState: "PInfo",
        nowState: {
          PInfo: { ifstate: true, title: "个人信息" },

          PSafety: { ifstate: false, title: "账号与安全" },
        },
        nowtitle: "个人信息",
      },
      //控制弹出层状态
      DialogVisible: {
        AccountDialogVisible: false,
        IdentifyDialogVisible: false,
        PhoneDialogVisible: false,
        EmailDialogVisible: false,
      },
      userid: this.$store.getters.UserInfoID,
      isUpImg: true,
      sexoptions: [
        {
          value: "1",
          label: "男",
        },
        {
          value: "2",
          label: "女",
        },
        {
          value: "3",
          label: "保密",
        },
      ],
      myInfo: {},
      pForm: {},
      pFormtimes: 0,
      PFormdisabled: true,
      pRules: {
        //校验用户名
        username: [{ validator: checkUsername, trigger: "blur" }],
        email: [
          { require: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur"],
          },
        ],
        phone: [
          {
            trigger: "blur",
          },
          { validator: validatePhone },
        ],
        age: [{ validator: validateAge2, trigger: "blur" }],
      },
      changeForm: {
        changeUseraccount: "",
        changeUserphone: "",
        changeUseremail: "",
        smscode: "",
      },
      CRules: {
        changeUseraccount: [
          { require: true, validator: validateUseraccount, trigger: "blur" },
        ],
        changeUserphone: [
          { require: true, validator: validatePhone, trigger: "blur" },
        ],
        changeUseremail: [
          { require: true, validator: validateEaiReg, trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
    changedata() {
      const { username, sex, age } = this.pForm;
      return {
        username,
        sex,
        age,
      };
    },
  },
  watch: {
    changedata() {
      this.pFormtimes++;
      if (this.pFormtimes > 1) {
        this.PFormdisabled = false;
      }
    },
  },
  methods: {
    //点击状态控制
    changeClickState(preState, nState) {
      this.clickstate.nowState[preState].ifstate = false;
      this.clickstate.prewState = nState;
      this.clickstate.nowState[nState].ifstate = true;
      this.clickstate.nowtitle = this.clickstate.nowState[nState].title;
    },
    //上传头像控制
    changeisUpImg() {
      this.isUpImg = !this.isUpImg;
    },
    //获取用户信息
    getUserInfo(userid) {
      this.axios
        .post("/user/getUserInfo", {
          userid: userid,
        })
        .then((res) => {
          if (res.data.data.code == 200) {
            this.myInfo = res.data.data.user;
            let { _id, username, sex, age } = this.myInfo;
            if (age == -1) {
              age = "未知";
            }
            this.pForm = { _id, username, sex, age };
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //更新用户名、年龄、性别
    updateUerInfo() {
      this.$refs.pForm.validate(async (valid) => {
        if (!valid) return false;
        else {
          this.axios
            .post("/user/updateUserInfo", this.pForm)
            .then((res) => {
              console.log(res);
              if (res.data.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.pForm.age = this.pForm.age == -1 ? "未知" : this.pForm.age;
                this.mergeObject(this.myInfo, this.pForm);
                this.$store.commit("updataUserInfo", {
                  username: this.pForm.username,
                });
                //改变按钮状态
                this.PFormdisabled = true;
                this.pFormtimes = 1;
              } else {
                this.$message.error("修改失败");
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("出错了哦");
            });
        }
      });
    },
    //对象赋值函数
    mergeObject(newObj, dataObj) {
      //newObj是需要的对象,dataObj是包含newObj键值对的大对象
      let Keys = Object.keys(newObj);
      for (let key in dataObj) {
        if (Keys.indexOf(key) > -1) {
          newObj[key] = dataObj[key];
        }
      }
    },
    updateUserAccount() {
      this.$refs.changeForm.validate(async (valid) => {
        if (!valid) return false;
        else {
          let userAccount = {
            account: this.changeForm.changeUseraccount,
            _id: this.userid,
          };
          this.axios
            .post("/user/updateUserAccount", userAccount)
            .then((res) => {
              if (res.data.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
              } else {
                this.$message.error("修改失败");
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("出错了哦");
            });
        }
      });
    },
    handleClose(done) {
      done();
    },
    changeSmsstate() {
      this.DialogVisible.IdentifyDialogVisible =
        !this.DialogVisible.IdentifyDialogVisible;
    },
    changePhoneState() {
      this.DialogVisible.PhoneDialogVisible =
        !this.DialogVisible.PhoneDialogVisible;
    },
    handleClosePhone(done) {
      done();
      this.$refs.phone.closestate();
    },
    hh() {
      this.DialogVisible.IdentifyDialogVisible = false;
      this.DialogVisible.PhoneDialogVisible = true;
    },
    newPhone(newp) {
      this.changePhoneState();
      this.myInfo.phone = newp;
    },
  },
  mounted() {
    this.getUserInfo(this.$store.getters.UserInfoID);
  },
};
</script>
<style scoped>
@import "../../assets/css/personal.css";
</style>
<style>
#form .el-input__inner {
  background-color: #f2f2f2;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606466;
  font-size: inherit;
  height: 48px;
  outline: 0;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
#accountDialog .el-dialog__title {
  text-align: center;
  display: block;
}
#accountDialog .el-input {
  margin-top: 23px;
}
#accountDialog .el-input__inner {
  background-color: #f2f2f2;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606466;
  font-size: inherit;
  height: 48px;
  outline: 0;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
</style>